package root.electronclass.electronclass.mvp.base;

import android.os.Handler;
import android.os.Looper;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * * 统一处理错误
 */
public abstract class CallbackNext<T> implements Callback<T> {
    private DialogViewModel mDialogViewModel;

    public abstract void onSuccessful(Call<T> call, T response);

    public abstract void onError(Call<T> call, T response);

    protected void onFail(Call<T> call, Throwable t, Response<T> response) {

    }

    public CallbackNext() {
    }

    public CallbackNext(DialogViewModel mDialogViewModel) {
        this.mDialogViewModel = mDialogViewModel;
    }

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        Handler mainHandler = new Handler(Looper.getMainLooper());
        mainHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                String url = response.raw().networkResponse().request().url().toString();

                if (mDialogViewModel != null && mDialogViewModel.multiRequest.getValue() != null) {//一个页面多接口请求计数接口请求完毕就关闭
                    mDialogViewModel.delRequest();
                }
                if (null != mDialogViewModel && mDialogViewModel.multiRequest.getValue() == null) {
                    mDialogViewModel.showProgressData.setValue(false);
                }
                if (response.code() == 200) {
                    BaseResponse<T> baseResponse = (BaseResponse<T>) response.body();
                    if (baseResponse.isSuccess()) {
                        CallbackNext.this.onSuccessful(call, response.body());
                    } else {
                        CallbackNext.this.onError(call, response.body());
                    }
                } else if (response.code() == 403) {
                    onFail(call, null, response);
                    if (null != mDialogViewModel) {
                        mDialogViewModel.showProgressData.setValue(false);
                        onFail(call, null, response);
                    }
                } else {
                    onFail(call, null, response);
                    if (null != mDialogViewModel) {
                        mDialogViewModel.showProgressData.setValue(false);
                        onFail(call, null, response);
                    }
                }

            }
        }, 500);
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        Handler mainHandler = new Handler(Looper.getMainLooper());
        mainHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (null != mDialogViewModel) {
                    mDialogViewModel.showProgressData.setValue(false);
                    mDialogViewModel.showExceptionData.setValue(t);
                    onFail(call, t, null);
                }
            }
        }, 500);
    }

}
